package src.实验5;



import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * Created by besti on 2018/6/9.
 */
public class SocketServer {

    public static void main(String[] args) throws IOException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, NoSuchPaddingException, NoSuchAlgorithmException, ClassNotFoundException {

        //1.建立一个服务器Socket(ServerSocket)绑定指定端口

        ServerSocket serverSocket=new ServerSocket(8800);

        //2.使用accept()方法阻止等待监听，获得新连接

        Socket socket=serverSocket.accept();

        //3.获得输入流

        InputStream inputStream=socket.getInputStream();

        BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));

        //获得输出流

        OutputStream outputStream=socket.getOutputStream();

        PrintWriter printWriter=new PrintWriter(outputStream);

        //4.读取用户输入信息

        byte []ctext = null;

        byte []temp = inputStream.readAllBytes();

        ctext = temp;

        if (ctext.length!=0) {

            System.out.print("加密后的内容; ");

            for(int i=0;i<ctext.length;i++){

                System.out.print( + ctext[i] +",");

            }

        }



        // 获取密钥

        // 读取对方的DH公钥

        FileInputStream f1=new FileInputStream("key1_pub.dat");

        ObjectInputStream b1=new ObjectInputStream(f1);

        PublicKey pbk=(PublicKey)b1.readObject( );

        //读取自己的DH私钥

        FileInputStream f2=new FileInputStream("key2_pri.dat");

        ObjectInputStream b2=new ObjectInputStream(f2);

        PrivateKey prk=(PrivateKey)b2.readObject( );

        // 执行密钥协定

        KeyAgreement ka=KeyAgreement.getInstance("DH");

        ka.init(prk);

        ka.doPhase(pbk,true);

        //生成共享信息

        byte[ ] sb=ka.generateSecret();

        for(int i=0;i<sb.length;i++) {

            System.out.print(sb[i] + ",");

        }

        SecretKeySpec k=new SecretKeySpec(sb,0,24,"AES");;

        // 解密

        Cipher cp=Cipher.getInstance("AES");

        cp.init(Cipher.DECRYPT_MODE, k);

        byte []ptext=cp.doFinal(ctext);

        // 显示明文

        String p = new String(ptext,"UTF8");



        System.out.println("\n后缀表达式：" + p);



        Caculator caculator = new Caculator();

        String a = caculator.getresult(p);



        System.out.println("计算结果为：" + a);



        //给客户一个响应

        String reply = a;

        printWriter.write(reply);

        printWriter.flush();



        //5.关闭资源

        printWriter.close();

        outputStream.close();

        bufferedReader.close();

        inputStream.close();

        socket.close();

        serverSocket.close();

    }


}
